<template>
  <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body :before-close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="产品" prop="appcode">
            <el-select
              v-model="form.appcode"
              @change="_productChange"
              placeholder="产品"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in productList"
                :key="item + index"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="渠道" prop="channel">
            <el-select v-model="form.channel" placeholder="渠道" filterable clearable style="width: 100%">
              <el-option
                v-for="(item, index) in channelList"
                :key="item + index"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button icon="el-icon-circle-plus-outline" size="mini" @click="_addSelectItem">添加</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="select-container clearfix" style="margin: 0 0 15px 80px;">
            <div
              class="select-item"
              v-for="(item, index) in appList"
              :key="item + index">
              {{item.appname}}({{item.channel}})
              <i class="el-icon-error" @click="_deleteSelectItem(index)"></i>
            </div>
          </div>
        </el-col>
      </el-row>
      <!-- <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="类型"
              @change="_changeAppType"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in appTypeList"
                :key="item + index"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="配置Key" prop="key">
            <el-select
              v-if="form.type === 0"
              v-model="form.key"
              @change="_configKeyChange(0)"
              placeholder="配置Key"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in dict.type.INNER_CONFIG_KEY"
                :key="item + index"
                :label="item.label"
                :value="item.value" />
            </el-select>
            <el-select
              v-if="form.type === 1"
              v-model="form.key"
              @change="_configKeyChange(1)"
              placeholder="配置Key"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in dict.type.OUT_CONFIG_KEY"
                :key="item + index"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row :gutter="24">
        <el-col :span="10">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入排序" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-query-row :label="'value'" :labelWidth="80" style="margin-bottom:0;">
        <!-- <el-col :span="12">
          <textarea v-model="form.textarea" :style="`height:302px;resize: none;`" placeholder="请输入内容" class="el-textarea__inner"></textarea>
        </el-col> -->
        <el-col :span="24">
          <b-code-editor v-model="form.jsonStr" :indent-unit="2" :height="`302px`" style="border: #C0C4CC 1px solid;" />
        </el-col>
      </el-query-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import commonMinxis from './common'
import { batchUpdateConfig } from '@/api/configs/appConfig.js'
export default {
  // dicts: ['INNER_CONFIG_KEY', 'OUT_CONFIG_KEY'],
  mixins: [commonMinxis],
  props: {
    title: {
      default: '支付宝配置',
      type: String
    },
    open: {
      default: false,
      type: Boolean
    }
  },
  data () {
    return {
      form: {
        appcode: '',
        appname: '',
        channel: '',
        type: 0,
        key: '',
        name: '',
        sort: 1,
        textarea: ' {    \"privateKey\": \"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDAVAtkLzynIy/2+eNPdJ3bauhT1e+N6qOi8IBNf+Usj5H01IxWrSQXLmrj+Zbb7zeikbT57SwKB9TSrlA9L1VHFj6ozmURwS3Xa33fIsOAuV+hziIDgXiZ0dsL877iwoyntB6v/tdnL/Dx8HQxxgiY2ypdcQz3EYbc1lk/IF9jfhKE2JvTwGhAJO+UTHAwIxUjZxqSgZG5Ywbc4NwgS/QGkpN6W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l/mVcP68xhMxdzawvCffPeR4OU27p+J6izVb/H1fRtr9c+5Y67YX+HUmBcVQoCUlg6sgsT68v7PnFtw+doaZ6rKwsohAoGAMHrCmgV01fYMe1Ww2l+59QStSptYJt36/y7xg8bHFq2rwhxn7PuVYa8ngxUgRn/8hz3l3NV+1SHwNEAsLuZOP2pKk4uCIa4YrAao7zBZcGT8/rE1z8WSGOVc+yWsuiYzdHn3I4DFkn5Aft7lAyp0m27A0AW0jUBmEjupO0h2MXA=\",    \"alipayPublicKey\": \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhV8NFm+glKXnD0AqfwfAJqQir/X3i5ln1N+jg0f25C93O8zucQKyM/tPci0nGwzLsWdOTnXeb+p1aHdsaxuFPXbyyNNxlZmx1MHzNFYaQsIp/qji6LMpj7yWzPGtDu+ClPi+R0HcDAm6YS6iBSZW/mAwG+X6vrxCJfYUaqLG4svWa4knxH+zf3NvJztRRpn76ZN9dthLIxtaylwaxV04Liu7XHUqHuXDlrNlZrWI42KaxoNQDBoIOrHQVJhFVeqBkNrkLEUJ7VC7rRZfs+iaIb2c8lWNxHtL0EJ1hVUdNfq+kqKNroe03evx5hG58AkADQsafCE5l4HmFf8Y78QjpwIDAQAB\",    \"appId\": \"2021003184635657\",    \"name\": \"汇流\"  }',
        jsonStr:  ' {    \"privateKey\": \"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDAVAtkLzynIy/2+eNPdJ3bauhT1e+N6qOi8IBNf+Usj5H01IxWrSQXLmrj+Zbb7zeikbT57SwKB9TSrlA9L1VHFj6ozmURwS3Xa33fIsOAuV+hziIDgXiZ0dsL877iwoyntB6v/tdnL/Dx8HQxxgiY2ypdcQz3EYbc1lk/IF9jfhKE2JvTwGhAJO+UTHAwIxUjZxqSgZG5Ywbc4NwgS/QGkpN6WJL7yn1pfikG9C8Q0xc6/kf0MqOu+aSMdIyZR3HC6LnqclhlvG4Hd5dSwuJmE+6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gsT68v7PnFtw+doaZ6rKwsohAoGAMHrCmgV01fYMe1Ww2l+59QStSptYJt36/y7xg8bHFq2rwhxn7PuVYa8ngxUgRn/8hz3l3NV+1SHwNEAsLuZOP2pKk4uCIa4YrAao7zBZcGT8/rE1z8WSGOVc+yWsuiYzdHn3I4DFkn5Aft7lAyp0m27A0AW0jUBmEjupO0h2MXA=\",    \"alipayPublicKey\": \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhV8NFm+glKXnD0AqfwfAJqQir/X3i5ln1N+jg0f25C93O8zucQKyM/tPci0nGwzLsWdOTnXeb+p1aHdsaxuFPXbyyNNxlZmx1MHzNFYaQsIp/qji6LMpj7yWzPGtDu+ClPi+R0HcDAm6YS6iBSZW/mAwG+X6vrxCJfYUaqLG4svWa4knxH+zf3NvJztRRpn76ZN9dthLIxtaylwaxV04Liu7XHUqHuXDlrNlZrWI42KaxoNQDBoIOrHQVJhFVeqBkNrkLEUJ7VC7rRZfs+iaIb2c8lWNxHtL0EJ1hVUdNfq+kqKNroe03evx5hG58AkADQsafCE5l4HmFf8Y78QjpwIDAQAB\",    \"appId\": \"2021003184635657\",    \"name\": \"汇流\"  }'

      },
      rules: {
        type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
        key: [{ required: true, message: '配置key不能为空', trigger: 'change' }],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
      },
      appList: [],
      productList: [],
      channelList: [],
      appTypeList: [{name: '应用内', value: 0}, ]
    }
  },
  watch: {
    'form.textarea' (value) {
      console.log(value)
      try {
        if(JSON.parse(value.trim())) {
          this.form.jsonStr = JSON.stringify(JSON.parse(value),null,2)
        }
      } catch (e) {
        console.log(e)
        this.form.jsonStr = `{}`
      }
    }
  },
  methods: {
    submitForm () {
      let vm = this;
      if (vm.appList.length === 0) {
        vm.$modal.msgError('请先添加产品和渠道');
        return false
      }
      vm.$refs["form"].validate(valid => {
        if (valid) {
          let { appcode, appname, channel, textarea, jsonStr, ...params } = vm.form;
          params.value = jsonStr.replace(/[ ]|[\r\n]/g, '');
          params.appList = vm.appList;
          batchUpdateConfig(params).then(response => {
            if (response.code === 200) {
              vm.$modal.msgSuccess('操作成功');
              //vm._resetForm()
              vm.cancel()
            } else {
              vm.$modal.msgError(response.msg);
            }
          });
        }
      });
    },
    _addSelectItem () {
      let vm = this;
      if (vm.form.appcode && vm.form.channel) {
        if (!vm._hasSelectItem()) {
          vm.appList.push({
            appcode: vm.form.appcode,
            appname: vm.form.appname,
            channel: vm.form.channel,
          });
        } else {
          vm.$modal.msgError('该产品渠道已存在');
        }
      } else {
        vm.$modal.msgError('请先选择产品和渠道');
      }
    },
    _hasSelectItem () {
      let vm = this;
      let status = vm.appList.some(item => {
        return item.appcode === vm.form.appcode && item.channel === vm.form.channel
      })
      return status
    },
    _deleteSelectItem (currIndex) {
      let vm = this;
      let newAppList = vm.appList.filter((item, index) => {
        return index !== currIndex
      });
      vm.$set(vm, 'appList', newAppList);
    },
    _resetForm () {
      let vm = this;
      vm.form = {
        appcode: '',
        appname: '',
        channel: '',
        type: 0,
        key: '',
        name: '',
        sort: 1,
        textarea: '',
        jsonStr: '{}'
      };
      vm.appList = [];
    },
    cancel () {
      this.$emit('update:open', false);
    }
  }
}
</script>

<style lang="scss" scoped>
.select-container {
  padding: 10px 10px 0;
  border: #e5e5e5 1px solid;
  border-radius: 3px;
  min-height: 48px;
  .select-item {
    position: relative;
    float: left;
    height: 26px;
    line-height: 26px;
    padding: 0 10px;
    background: #e5e5e5;
    border-radius: 3px;
    margin-right: 10px;
    margin-bottom: 10px;
    cursor: pointer;
    &:hover {
      .el-icon-error {
        display: block;
      }
    }
    .el-icon-error {
      display: none;
      position: absolute;
      top: -3px;
      right: -3px;
      color: red;
      cursor: pointer;
    }
  }
}
</style>
